package cn.nfwx.tv.helper;

import android.content.Context;
import android.text.TextUtils;

import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import cn.nfwx.tv.BuildConfig;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.DeviceUtil;

/**
 * Created by dell on 2018/1/26.
 */

public class BuglyHelper {

    private static BuglyHelper instance;

    public static BuglyHelper getInstance() {
        if (instance == null) {
            synchronized (BuglyHelper.class) {
                if (instance == null) {
                    instance = new BuglyHelper();
                }
            }
        }
        return instance;
    }


    public void init(Context context) {
        if (BuildConfig.IS_RELEASE) { // 线上
            CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
            // 获取当前包名
            String packageName = context.getPackageName();
            // 获取当前进程名
            String processName = getProcessName(android.os.Process.myPid());
            strategy.setAppPackageName(packageName);
            strategy.setUploadProcess(processName == null || processName.equals(packageName));
            strategy.setAppChannel(AppUtil.getChannel(context));
            strategy.setAppVersion(AppUtil.getCrrentName(context));
            strategy.setDeviceID(DeviceUtil.generateDeviceId(context));
            CrashReport.initCrashReport(context, "39d365f3f5", false, strategy);//bugly
        } else { // 测试
            CrashReport.initCrashReport(context, "5eee8c8a1a", true);//bugly
        }
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
